﻿using System;
using System.IO;
using System.Net;
using System.Text;

namespace Web
{
    public class Utility
    {


        public static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
        {
            string ret = string.Empty;
            byte[] byteArray = dataEncode.GetBytes(paramData); //转化
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
            webReq.Method = "POST";
            webReq.ContentType = "application/x-www-form-urlencoded";

            webReq.ContentLength = byteArray.Length;
            Stream newStream = webReq.GetRequestStream();
            newStream.Write(byteArray, 0, byteArray.Length);//写入参数
            newStream.Close();
            HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            ret = sr.ReadToEnd();
            sr.Close();
            response.Close();
            newStream.Close();

            return ret;
        }

        /// <summary> 通过URL获取远程服务器的数据 </summary>
        /// <param name="url">请求地址</param>
        /// <returns>远程服务器返回的数据</returns>
        public static string GetWebRequest(string url)
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
            myRequest.Method = "get";
            myRequest.ContentType = "text/html";
            //接受返回的数据

            HttpWebResponse res = (HttpWebResponse)myRequest.GetResponse();
            StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.UTF8);
            string backstr = sr.ReadToEnd();

            sr.Close();
            res.Close();

            return backstr;
        }
    }
}